﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace KiraSh.ResumeTracker
{
    public static class CompanyManager
    {
        public static string companyPath = PathHelper.MapCombine(CurrentContext.Profile.Name, "companies.xml");

        private static List<Company> companies;

        public static void LoadFromDisk()
        {
            LoadFromDisk(companyPath);
        }

        public static void LoadFromDisk(string path)
        {
            XMLDealer xml = new XMLDealer();
            if (File.Exists(path))
            {
                companies = (List<Company>)xml.LoadXML(path, typeof(List<Company>));
                if (companies == null)
                {
                    throw new Exception("Companies file invalid. " + path);
                }
            }
            else
            {
                companies = new List<Company>();
            }
        }

        public static void SaveToDisk()
        {
            SaveToDisk(companyPath);
        }

        public static void SaveToDisk(string path)
        {
            XMLDealer xml = new XMLDealer();

            if (companies == null)
            {
                throw new Exception("Companies are null. Please load from disk first.");
            }
            xml.WriteXML(path, typeof(List<Company>), companies);
        }

        public static List<Company> Companies
        {
            get
            {
                return companies;
            }
        }

        public static Company CreateNewCompany(string name)
        {
            // create temp company and get the selection from the drop box
            Company newCompany = new Company();

            // create new company object
            if (name.Trim().Length > 0)
            {
                newCompany.Name = name;
                // make sure the company doesn't already exist
                if (companies.Contains(newCompany))
                {
                    throw new Exception("Company " + name + " already exists.");
                }
                else
                {
                    newCompany.Path = PathHelper.Combine(CurrentContext.Profile.Name, "companies", newCompany.Name + ".xml");
                    // add company to the list and xml file
                    Companies.Add(newCompany);
                    return newCompany;
                }
            }
            else
            {
                throw new Exception("Company name cannot be empty.");
            }
        }

    }
}
